package segmenttree;

/**
 * 线段树 (区间树),其实就是用树来表示数组的区间
 * @param <E>
 */
public class SegmentTree<E> {
    private E[] data;
    private E[] tree;
    private Merger<E> merger;

    public SegmentTree(E[] arr, Merger<E> merger){
        this.merger = merger;

        data = (E[])new Object[arr.length];
        for (int i = 0; i < arr.length; i++) {
            data[i] = arr[i];
        }

        tree = (E[]) new Object[4 * arr.length]; // why 开辟4n个空间? 因为是平衡二叉树结构(本身该层n个,上面所有加起来约n个),然后虚拟null节点形成满二叉树(约2n个)
        buildSegmentTree(0, 0, data.length - 1);
    }

    // 在treeIndex的位置创建表示区间[l...r]的线段树
    private void buildSegmentTree(int treeIndex, int l, int r) {

        if(l == r) {
            tree[treeIndex] = data[l];
            return;
        }

        int leftChildIndex = leftChild(treeIndex);
        int rightChildIndex = rightChild(treeIndex);
        int mid = l + (r - l) / 2;

        buildSegmentTree(leftChildIndex, l, mid);
        buildSegmentTree(rightChildIndex, mid + 1, r);

        tree[treeIndex] = merger.merge(tree[leftChildIndex], tree[rightChildIndex]);
    }

    public int getSize(){
        return data.length;
    }

    public E get(int index){
        if (index < 0 || index >= data.length) {
            throw new IllegalArgumentException("index is illegal");
        }
        return data[index];
    }

    /**
     * O(logn)
     * @param queryL
     * @param queryR
     * @return
     */
    public E query(int queryL, int queryR){
        if(queryL < 0 || queryL > data.length || queryR < 0 || queryR > data.length
            || queryL > queryR){
            throw new IllegalArgumentException("传入范围错误");
        }
        return query(0,0, data.length-1, queryL, queryR);
    }

    private E query(int treeIndex, int l, int r, int queryL, int queryR) {
        if(l == queryL && r == queryR){
            return tree[treeIndex];
        }
        int leftChildIndex = leftChild(treeIndex);
        int rightChildIndex = rightChild(treeIndex);

        int mid = l + (r - l) / 2;
        if(queryL >= mid + 1) {
            return query(rightChildIndex, mid + 1, r, queryL, queryR);
        } else if(queryR <= mid){
            return query(leftChildIndex, l,mid,queryL,queryR);
        } else {
            E leftResult = query(leftChildIndex, l, mid, queryL, mid);
            E rightResult = query(rightChildIndex, mid+1,r,mid+1,queryR);
            return  merger.merge(leftResult,rightResult);
        }

    }

    // 将index位置的值,更新为e
    public void set(int index, E e){
        if(index < 0 || index >= data.length){
            throw new IllegalArgumentException("index is illegal");
        }
        data[index] = e;

        set(0, 0, data.length-1, index, e);
    }

    /**
     * 在以treeIndex为根的线段树中更新index的值为e, LogN复杂度
     * @param treeIndex 线段树的索引
     * @param l 数组左边的索引
     * @param r 数组右边的索引
     * @param index 要更新的索引
     * @param e 更新的值
     */
    private void set(int treeIndex, int l, int r, int index, E e){

        if(l == r){
            tree[treeIndex] = e;
            return;
        }
        int mid = l + (r - l) / 2;
        int leftChildIndex = leftChild(treeIndex);
        int rightChildIndex = rightChild(treeIndex);

        if(index >= mid + 1){
            set(rightChildIndex, mid+1, r,index,e);
        } else {
            set(leftChildIndex,l,mid, index, e);
        }
        tree[treeIndex] = merger.merge(tree[leftChildIndex], tree[rightChildIndex]);
    }

    private int leftChild(int index){
        return 2 * index + 1;
    }

    private int rightChild(int index){
        return 2 * index + 2;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append('[');
        for (int i = 0; i < tree.length; i++) {
            if(tree[i] != null){
                res.append(tree[i]);
            }else {
                res.append("null");
            }
            if( i != tree.length-1){
                res.append(",");
            }
        }
        res.append(']');
        return res.toString();

    }

    public static void main(String[] args) {
        Integer[] nums = {-2, 0, 3, -5, 2, -1};
        SegmentTree<Integer> segmentTree = new SegmentTree<>(nums, (a, b) -> a + b);
//        System.out.println(segmentTree);

        System.out.println(segmentTree.query(0,2));
    }
}
